package com.shawn.integeration.ratelimiter.aspect;

import com.shawn.integeration.ratelimiter.annonation.RateLimiter;
import com.shawn.integeration.ratelimiter.expcetion.AccessTooFrequentException;
import com.shawn.integeration.ratelimiter.service.IRateLimiterService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 限流切面,用于拦截 web 请求,进行拦截
 *
 * @author: shawn
 * @Date: 2023/12/28 10:36
 * @Version 1.0.0
 */
@Slf4j
@Aspect
@Component
public class RateLimiterAspect {
    @Resource
    private IRateLimiterService limiterService;

    @Before("@annotation(rateLimiter)")
    public void doBefore(JoinPoint joinPoint, RateLimiter rateLimiter) {
        try {
            boolean canAccess = limiterService.canAccess(joinPoint, rateLimiter);
            if (!canAccess) {
                throw new AccessTooFrequentException();
            }
        } catch (AccessTooFrequentException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("服务器限流异常，请稍候再试");
        }
    }
}
